package edu.gatech.oad.yuno;

import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo; 
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;

import java.util.List;
import java.util.Date;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.*;
import android.view.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.AdapterContextMenuInfo;

/**
 * This activity is responsible for the login screen and the main screen.
 * @author michael
 *
 */
public class YUNoDosActivity extends Activity implements View.OnClickListener, OnKeyListener {
	private Button buttonLogin;
	private Button buttonRegister;
	private TextView textForgotPassword;
	private EditText editUsername;
	private EditText editPassword;
	
	private LinearLayout titleBar;
	private TextView titleText;
	private TextView titleX;
	private ListView mainList;
	private ImageButton quickAdd;
	private EditText editQuickAdd;
	private Menu menu;
	
	private boolean loggedIn = false;
	
	private ArrayAdapter<Todo> mainListAdapter;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences prefs = getSharedPreferences("YUNoDos", MODE_PRIVATE);
                
        if (prefs.getLong("logged_in_user_id", 0) == 0) {
        	loggedIn = false;
        	setUpLogin();
        } else {
        	loggedIn = true;
        	setUpMain();
        }
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	if(loggedIn) reloadList();
    }
    
    @Override
    public void onClick(View v) {
    	if (v == buttonLogin) {
	    	if (User.login(editUsername.getText().toString(), 
	    			editPassword.getText().toString())) {
	    		SharedPreferences prefs = getSharedPreferences("YUNoDos", MODE_PRIVATE);
	    		SharedPreferences.Editor editor = prefs.edit();
	    		User user = User.find(editUsername.getText().toString());
	    		if (user != null) {
	    			editor.putLong("logged_in_user_id", user.getId());
	    			editor.putLong("filter_startdate",0);
	    	    	editor.putLong("filter_enddate",0);
	    	    	editor.putInt("filter_priority",0);
	    	    	editor.putLong("filter_location", 0);
	    	    	editor.putLong("filter_category",0);
	    			editor.commit();
	    			//editor.putBoolean("ShowAll", false);
	    		}
	    		loggedIn = true;
	    		setUpMain();
	    		reloadList();
	    	} else {
	    		Toast.makeText(this, "Invalid username or password.",
	    				Toast.LENGTH_SHORT).show();
	    	}
    	} else if (v == buttonRegister) {
    		Intent intent = new Intent(this, RegisterActivity.class);
    		startActivity(intent);
    	} else if (v == textForgotPassword) {
    		Intent intent = new Intent(this, ForgotPasswordActivity.class);
    		startActivity(intent);
    	} else if (v==quickAdd){
    		if (editQuickAdd.getText().toString().equals("")) {
    			Intent intent = new Intent(this, AddTodoActivity.class);
    			startActivity(intent);
    		} else {
    			Todo todo = new Todo();
    			SharedPreferences prefs = getSharedPreferences("YUNoDos", MODE_PRIVATE);
    			todo.setUser(prefs.getLong("logged_in_user_id", 0));
    			todo.setName(editQuickAdd.getText().toString());
    			try {
    				todo.validate();
    				todo.save();
    				reloadList();
    				Toast.makeText(getApplicationContext(),editQuickAdd.getText().toString() + " added.",
    						Toast.LENGTH_SHORT).show();
    				editQuickAdd.setText("");
    			} catch (ValidationException e) {
    				Toast.makeText(this, e.getMessage(),
    	    				Toast.LENGTH_SHORT).show();
    			}
    		}
    	}
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	this.menu=menu;
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    	return loggedIn;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.logOut:
            	SharedPreferences prefs = getSharedPreferences("YUNoDos", MODE_PRIVATE);
	    		SharedPreferences.Editor editor = prefs.edit();
	    		editor.putLong("logged_in_user_id", 0);
	    		editor.commit();
	    		loggedIn = false;
	    		setUpLogin();
                return true;
            case R.id.item1:
        		Intent intent = new Intent(this, AddTodoActivity.class);
        		startActivity(intent);
        		return true;
            case R.id.item2:
            	intent = new Intent(this, FilterActivity.class);
            	startActivity(intent);
            	return true;
            case R.id.showCompleted:
            	prefs = getSharedPreferences("YUNoDos", MODE_PRIVATE);
            	editor = prefs.edit();
            	if (!prefs.getBoolean("ShowAll", false)){
            		editor.putBoolean("ShowAll", true);
                	item.setTitle("Hide Completed");
            	}
            	else{
            		editor.putBoolean("ShowAll", false);
            		item.setTitle("Show Completed");
            	}
            	editor.commit();
            	reloadList();
            	return true;
            case R.id.item3:
            	intent = new Intent(this, MapActivity.class);
            	startActivity(intent);
            	return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    
    /**
     * Display the login screen
     */
    private void setUpLogin() {
    	setContentView(R.layout.login);
    	buttonLogin = (Button) findViewById(R.id.buttonLogin);
    	buttonRegister = (Button) findViewById(R.id.buttonRegister);
    	textForgotPassword = (TextView) findViewById(R.id.textForgotPassword);
    	editUsername = (EditText) findViewById(R.id.editUsername);
    	editPassword = (EditText) findViewById(R.id.editPassword);
    	
    	buttonLogin.setOnClickListener(this);
    	buttonRegister.setOnClickListener(this);
    	textForgotPassword.setOnClickListener(this);
    }
    
    /**
     * Display the main screen
     */
    private void setUpMain() {
    	setContentView(R.layout.main);
    	titleBar = (LinearLayout) findViewById(R.id.titleBar);
    	titleText = (TextView) findViewById(R.id.titleText);
    	titleX = (TextView) findViewById(R.id.titleX);
    	mainList = (ListView) findViewById(R.id.mainList);
    	mainList.setOnItemClickListener(new OnItemClickListener(){
    		public void onItemClick(AdapterView<?> parent, View view,
    		    int position, long id) {
    			//go to view of specific todo that user clicked.
    			Todo todo=(Todo) parent.getAdapter().getItem(position);
    			openViewItem(todo);
    		}
    	});
    	   	
    	quickAdd = (ImageButton) findViewById(R.id.quickAdd);
    	quickAdd.setOnClickListener(this);
    	
    	editQuickAdd = (EditText) findViewById(R.id.editQuickAdd);
    	editQuickAdd.setOnKeyListener(this);
    }
    
    public void openViewItem(Todo todo){
    	Intent intent = new Intent(this, ViewTodoActivity.class);
    	System.out.println(todo.getId());
    	intent.putExtra("ToDo", todo.getId()); //this is the method to send an object from activity to activity
		startActivity(intent);
	}

    public void openEditItem(Todo todo){
    	Intent intent = new Intent(this, AddTodoActivity.class);
    	intent.putExtra("ToDo", todo.getId()); //this is the method to send an object from activity to activity
		startActivity(intent);
	}
    
    /**
     * Refresh the list of tasks
     */
    private void reloadList() {
    	SharedPreferences prefs = getSharedPreferences("YUNoDos", MODE_PRIVATE);
    	List<Todo> list=Todo.findAllByUser(prefs.getLong("logged_in_user_id", 0));
    	long startDate = prefs.getLong("filter_startdate",0);
    	long endDate = prefs.getLong("filter_enddate",0);
    	int priority = prefs.getInt("filter_priority",0);
    	long locationId = prefs.getLong("filter_location", 0);
    	long categoryId = prefs.getLong("filter_category",0);
    	Date dateStart = (startDate==0) ? null : new Date(startDate);
    	Date dateEnd = (endDate==0) ? null : new Date(endDate);
    	list = SearchProvider.filter(prefs.getLong("logged_in_user_id", 0),
    			priority, locationId, categoryId, 
    			dateStart, dateEnd);
    	if (!prefs.getBoolean("ShowAll", false))
    		list=SearchProvider.excludeCompleted(list);
    	if (startDate == 0 && endDate == 0 && priority == 0 && locationId == 0
    			&& categoryId == 0) {
    		titleBar.setVisibility(View.GONE);
    	} else {
    		String title = "";
    		if (priority > 0)
    			for (int i = 0; i < priority; i++)
            		title += "*";
    		if (locationId != 0)
    			title = (new Location(locationId)).getName();
    		if (categoryId != 0)
    			title = (new Category(categoryId)).getName();
    		if (startDate != 0)
    			title = "After "+DateHelper.format(new Date(startDate));
    		if (endDate != 0) {
    			if (startDate != 0) title += " and ";
    			title += "Before "+DateHelper.format(new Date(endDate));
    		}
    		titleText.setText(title);
    		titleBar.setVisibility(View.VISIBLE);
    	}
    	mainListAdapter=new TodoListAdapter(this, R.layout.todo_row, list); 
    	mainList.setAdapter(mainListAdapter); 
    	registerForContextMenu(mainList); 
    }
    
   
    public void onCreateContextMenu(ContextMenu menu, View v,
    	    ContextMenuInfo menuInfo) {
    	  if (v.getId()==R.id.mainList) {
    	    AdapterContextMenuInfo info = (AdapterContextMenuInfo)menuInfo;
    	    menu.setHeaderTitle("Options"); //change to todo name?
    	      menu.add(Menu.NONE, 0, Menu.NONE, "View");
    	      menu.add(Menu.NONE, 1, Menu.NONE, "Edit");
    	      menu.add(Menu.NONE, 2, Menu.NONE, "Show on map");
    	      menu.add(Menu.NONE, 3, Menu.NONE, "Delete");
    	  }
    	}
    
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    	Todo todo=mainListAdapter.getItem(info.position);
    	switch (item.getItemId()) {
    	case 0: //View
    		openViewItem(todo);
    		return true;
    	case 1: //Edit
    		openEditItem(todo);
    		return true;
    	case 2: 
    		return true;
    	case 3://Delete
    		todo.delete();
    		reloadList();
        	Toast.makeText(getApplicationContext(), todo.getName() +" deleted.",
					Toast.LENGTH_SHORT).show();
    		return true; 
    	}
    	return false;
    }
    
    public void onCheckBox(View v) {
    	Todo todo = (Todo)mainList.getItemAtPosition(mainList.getPositionForView(v));
    	todo.setCompleted(((CheckBox)v).isChecked());
    	todo.save();
    	mainList.invalidateViews();
    	reloadList();
    }

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_ENTER && 
				event.getAction() == KeyEvent.ACTION_UP && 
				(event.getFlags() & KeyEvent.FLAG_CANCELED) == 0) {
			quickAdd.performClick();
		}
		return false;
	}
}